package com.nexgo.payment.action.inputdate;

import android.support.annotation.NonNull;

import com.nexgo.payment.aop.annotation.RunOnMainThread;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.util.RegexUtils;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.widget.keyboard.NumKeyBoard;
import com.nexgo.sound.BeeperManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 授权码输入操作
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年8月25日
 */
public class InputDatePresenter implements InputDateContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(InputDatePresenter.class.getSimpleName());

    private final BeeperManager mBeeperManager;
    private InputDateContract.View mView;
    private DataSource mRepository;
    private StringBuilder mBuilder;

    public InputDatePresenter(@NonNull InputDateContract.View view, @NonNull DataSource repository) {
        mView = checkNotNull(view);
        mRepository = checkNotNull(repository);
        view.setPresenter(this);
        mBuilder = new StringBuilder();
        mBeeperManager = new BeeperManager();
    }

    @Override
    public void start() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void pressKey(NumKeyBoard.KEY_TYPE keyType) {
        mBeeperManager.beep(BeeperManager.Type.NORMAL);
        switch (keyType) {
            case KEY_0:
            case KEY_1:
            case KEY_2:
            case KEY_3:
            case KEY_4:
            case KEY_5:
            case KEY_6:
            case KEY_7:
            case KEY_8:
            case KEY_9:
                addKey(keyType);
                break;
            case KEY_BACKSPACE:
                if (mBuilder.length() == 0) {
                    return;
                }
                mBuilder.deleteCharAt(mBuilder.length() - 1);
                mLog.debug("退格后的内容：{}", mBuilder.toString());
                postMainThread(() -> mView.showInputResult(mBuilder.toString()));
                break;
            case KEY_CANCEL:
                mBuilder.setLength(0);
                postMainThread(() -> mView.showCancel());
                break;
            case KEY_CONFIRM:
                if (mBuilder.length() == 0) {
                    postMainThread(() -> mView.showEmpty());
                    return;
                }
                mLog.debug("确认输入日期，长度：{}，内容：{}", mBuilder.length(), mBuilder.toString());
                if (mBuilder.length() != 4 || !verifyDate(mBuilder.toString())) {
                    postMainThread(() -> mView.showErrFormat());
                    mBuilder.setLength(0);
                    postMainThread(() -> mView.showInputResult(mBuilder.toString()));
                    return;
                }
                postMainThread(() -> mView.showConfirm(mBuilder.toString()));
                break;
            default:
                break;
        }
    }

    /**
     * 添加输入数字
     *
     * @param keyType
     */
    private void addKey(NumKeyBoard.KEY_TYPE keyType) {
        if (mBuilder.length() == 4) {
            return;
        }
        mBuilder.append(keyType.getKeyValue());
        mLog.debug("输入内容：{}", mBuilder.toString());
        postMainThread(() -> mView.showInputResult(mBuilder.toString()));
    }

    /**
     * 校验输入日期是否符合
     *
     * @param dateStr 格式MMdd
     * @return 返回检验值
     */
    private boolean verifyDate(String dateStr) {
        StringBuilder sb = new StringBuilder();
        sb.append(String.valueOf(StringUtils.getCalenderField(Calendar.YEAR)));
        sb.append("-");
        sb.append(dateStr.substring(0, 2));
        sb.append("-");
        sb.append(dateStr.substring(2, 4));
        mLog.debug("转化格式后日期：{}", sb.toString());
        return RegexUtils.isDate(sb.toString());
    }

    @RunOnMainThread
    private void postMainThread(Runnable runnable) {
        if (mView.isActive()) {
            runnable.run();
        }
    }
}
